package com.cskaoyan.controller.admin.authcontroller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.Serializable;

@Controller
public class AuthController2 {

    @RequestMapping(value = "/index")
    public String index(){
        return "index"; //templates/index.ftlh
    }

//    @RequestMapping("unAuthc")
//    public String unAuthc(){
//        return "forward:/index";
//    }

    /*
    * 认证
    * */
    @RequestMapping("auth/login")
    @ResponseBody
    public String login(String username,String password){
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
        } catch (AuthenticationException e) {
            return "forward:/index";
            //e.printStackTrace();
        }
        Serializable id = subject.getSession().getId();
        return (String) id;
    }
    //在真正之前先访问success
    //认证通过之后在访问success
    @RequestMapping("success")
    public String success(){
        return "success";
    }

    /*
    * need/perm
    * 使用这个RequiresPermissions需要aspectj支持
    * 引入aspectjweaver的支持包
    * 需要注册一个advisor
    * */
    @RequestMapping("need/perm")
    @RequiresPermissions(value = {"perm1","perm2"},logical = Logical.OR)
    public String needPerm(){
        Subject subject = SecurityUtils.getSubject();
        Object primaryPrincipal = subject.getPrincipals().getPrimaryPrincipal();

        return "permission";
    }

    @RequestMapping("noperm")
    public String noperm(){

        return "noperm";
    }
    @RequestMapping("auth/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "/index";
    }



}
